<?php


namespace app\common\model\mysql;


use app\common\exception\MessageException;

class GoodsImage extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'mall_goods_image';

    // 定义主键
    protected $pk = 'id';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 隐藏字段
    protected $hidden=['id', 'goods_id', 'sort', 'create_time'];

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    /**
     * 关联文件库
     * @return \think\model\relation\BelongsTo
     */
    public function file()
    {
        return $this->belongsTo('DriverFile', 'image_id', 'id')->bind(['image_path' => 'file_path']);
    }

    /**
     * 批量写入商品图片记录
     * @param int $goodsId
     * @param array $imageIds
     * @return array|false
     */
    public static function increased(int $goodsId, array $imageIds): bool|array
    {
        if (!is_array($imageIds)) {
            throw new MessageException(['msg' => '传递参数错误']);
        }

        $dataset = [];
        foreach ($imageIds as $key => $imageId)  {
            $dataset[] = [
                'image_id' => $imageId,
                'goods_id' => $goodsId,
                'sort' => $key
            ];
        }
        return (new static)->addAll($dataset);
    }

    /**
     * 更新关系记录
     * @param int $goodsId
     * @param array $imageIds 新的图片集
     * @return array|false
     */
    public static function updates(int $goodsId, array $imageIds): bool|array
    {
        // 删除所有的sku记录
        static::deleteAll(['goods_id' => $goodsId]);
        // 批量写入商品图片记录
        return static::increased($goodsId, $imageIds);
    }
}